package pub.cleangao.memm.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import pub.cleangao.memm.registry.RpcRuntime;
import pub.cleangao.memm.util.ThreadPoolFactory;

import java.util.Set;
import java.util.concurrent.ExecutorService;

@Component
@Slf4j
public class AfterApplicationStart implements InitializingBean {

    private final ExecutorService async = ThreadPoolFactory.createThreadPoolIfAbsent("rpc-server");

    @Override
    public void afterPropertiesSet() throws Exception {
        async.execute(() -> {
            Set<String> serveNode = RpcRuntime.getRegistry().allServeNode();
            if (serveNode == null || serveNode.isEmpty()) {
                return;
            }
            for (String hostPort : serveNode) {
                if (!RpcRuntime.testConnection(hostPort)) {
                    log.info("Rpc node initialized clear remote dead storage: {}", hostPort);
                    RpcRuntime.getRegistry().removeRemoteNode(hostPort);
                }
            }
        });

    }
}
